<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="10">
        <el-card
          class="box-construction"
          shadow="always"
          v-loading="loading"
          :style="`height:${Height}px`"
        >
          <div class="box-title box-title-position">
            <div>考核关系</div>
            <el-button
              class="add-btn"
              size="medium"
              type="primary"
              @click="addOrg()"
              >新增组织</el-button
            >
          </div>
          <el-tree
            ref="asyncTree"
            check-strictly
            highlight-current
            show-checkbox
            :expand-on-click-node="false"
            node-key="id"
            :props="treeDefaultProps.defaultProps"
            :load="loadNode"
            lazy
            @check-change="handleCheckChange"
            @node-click="handleNodeClick"
            :style="`width: 100%;margin-top:30px;min-height:100px;max-height:${
              Height - 100
            }px;overflow: auto;`"
          >
            <div class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>
              <span>
                <el-button
                  :type="'text'"
                  size="mini"
                  @click.prevent.stop="() => nodeEdit(data)"
                  >编辑</el-button
                >
                <el-button
                  v-if="data.pid != 0"
                  :type="'text'"
                  size="mini"
                  @click.prevent.stop="() => nodeDel(node, data)"
                  >删除</el-button
                >
              </span>
            </div>
          </el-tree>
        </el-card>
      </el-col>
      <el-col v-if="!isAddOrg" :span="14">
        <el-card
          class="box-construction"
          shadow="always"
          v-loading="peoloading"
          :style="`height:${Height}px`"
        >
          <div class="box-title-position">
            <el-button
              class="add-btn"
              size="medium"
              type="primary"
              @click="addUser(true)"
              >批量添加</el-button
            >
            <el-button
              class="add-btn"
              size="medium"
              type="primary"
              @click="addUser(false)"
              >添加人员</el-button
            >
          </div>
          <el-table
            size="small"
            :show-header="false"
            :data="tableData"
            :max-height="`${Height - 100}`"
            style="width: 100%; margin-top: 40px"
          >
            <el-table-column prop="name" label="姓名"></el-table-column>
            <el-table-column prop="kp_name" label="职位">
              <template slot-scope="scope">
                <!-- <span>{{scope.row.kp==1?"日常打分":"质量打分"}}</span> -->
                <span>{{
                  scope.row.kp_name && scope.row.kp_name != null
                    ? scope.row.kp_name
                    : ""
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="version" label="操作" width="90">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="mini"
                  @click="editPeople(scope.row)"
                  >编辑</el-button
                >
                <el-button type="text" size="mini" @click="delPeople(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col v-else :span="14">
        <el-card
          class="box-construction"
          shadow="always"
          :style="`height:${Height}px`"
        >
          <div class="box-title box-title-position">
            <div>{{ orgTitle }}</div>
          </div>
          <div class="org-content">
            <span class="org-label">组织名称</span>
            <el-input v-model="orgname" placeholder="请输入"></el-input>
          </div>
          <div class="btn-box">
            <el-button size="small" @click="closeAdd">取消</el-button>
            <el-button
              :type="'primary'"
              size="small"
              :loading="saveLoading"
              @click="saveOrg"
              >保存</el-button
            >
          </div>
        </el-card>
      </el-col>
    </el-row>
    <EditForm
      ref="form"
      v-if="visible"
      :isMore="isMore"
      :title="formTitle"
      :datas.sync="editRow"
      :classData="classData"
      :visible.sync="visible"
      :baseStyle="baseStyle"
      @saveForm="submitForm"
    />
  </div>
</template>

<script>
import orgAPI from "@apis/organize";
import perSetAPI from "@apis/performanceSet";
// import { mapState } from "vuex";
import EditForm from "./editForm/index";
export default {
  data() {
    return {
      classData: [],
      visible: false,
      isMore: false,
      isAddUser: false,
      editRow: {},
      formTitle: "添加人员",
      addPeople: { orgid: "", orgname: "" }, //添加人员时的组织ID
      baseStyle: {
        width: "120px",
      },

      loading: false,
      peoloading: false,
      data: [],
      node_zero: "", // 将node.level == 0的node存起来
      resolve_zero: "", // 将node.level == 0的resolve存起来
      treeDefaultProps: {
        defaultProps: {
          children: "children",
          label: "label",
        },
        defaultExpanded: [1],
      },
      tableData: [],
      orgTitle: "组织新增",
      isAddOrg: false,
      isEdit: false,
      saveLoading: false,
      orgname: "",
      curTreeNode: {},
    };
  },
  components: {
    EditForm,
  },
  computed: {
    // ...mapState({
    //   userInfo: "auth",
    // }),
    Height() {
      return document.documentElement.clientHeight - 110;
    },
  },
  created() {
    this.getClassList();
  },
  mounted() {},
  methods: {
    //获取弹窗中的类型数据
    getClassList() {
      let parmars = {
        pageNo: 1,
        pageSize: 1000,
      };
      perSetAPI
        .classicGetList(parmars)
        .then((res) => {
          this.classData = [{ id: 0, name: "无" }, ...res.data];
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
    },
    //新增删除节点后的更新函数
    refreshNodeBy(id) {
      if (id != 0) {
        let node = this.$refs.asyncTree.getNode(id); // 通过节点id找到对应树节点对象
        node.loaded = false;
        node.expand(); // 主动调用展开节点方法，重新查询该节点下的所有子节点
      } else {
        this.loadNode(this.node_zero, this.resolve_zero);
      }
    },
    //树状图数据懒加载函数
    async loadNode(node, resolve) {
      this.loading = true;
      if (node.level == 0) {
        this.node_zero = node;
        this.resolve_zero = resolve;
        this.node_zero.childNodes = [];
        await this.getOrgList(0);
        return resolve(this.data);
        // this.peoloading = true;
        // this.getPeopleList(this.data[0].id);
      } else {
        await this.getOrgList(node.data.id);
        return resolve(this.data);
        // this.peoloading = true;
        // this.getPeopleList(node.data.id);
      }
    },
    //获取树状图数据
    async getOrgList(val = 0) {
      this.data = [];
      let parmars = {
        pid: val,
        pageNo: 1,
        pageSize: 1000,
      };
      await orgAPI
        .getOrgList(parmars)
        .then((res) => {
          res.data.map((item) => {
            this.data.push({
              pid: item.pid,
              id: item.id,
              label: item.orgname ? item.orgname : "label" + item.id,
              children: [],
            });
          });
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
          this.$message.error(err.message);
        });
    },
    //勾选选中
    handleCheckChange(data, checked, indeterminate) {
      var getlist = this.$refs.asyncTree
        .getCheckedNodes()
        .concat(this.$refs.asyncTree.getHalfCheckedNodes());
      for (var i in getlist) {
        if (getlist.length == 1) {
          this.curTreeNode = { ...data };
        } else {
          this.curTreeNode = {};
          this.isAddOrg = false;
          this.$message.warning("只能选择一个节点");
          this.$refs.asyncTree.setCheckedKeys([]);
          return;
        }
      }
    },
    handleNodeClick(data, node, nodeSelf) {
      // console.log(data, node, nodeSelf);
      this.peoloading = true;
      this.addPeople = { orgid: data.id, orgname: data.label }; //添加人员所在组织ID
      this.getPeopleList(data.id);
    },
    //新增组织
    addOrg() {
      var getlist = this.$refs.asyncTree
        .getCheckedNodes()
        .concat(this.$refs.asyncTree.getHalfCheckedNodes());
      if (getlist.length > 0) {
        this.curTreeNode = { ...getlist[0] };
        this.orgname = "";
        this.orgTitle = "组织新增";
        this.isEdit = false;
        this.isAddOrg = true;
      } else {
        this.$message.warning("请先勾选父节点");
      }
    },
    closeAdd() {
      this.orgname = "";
      this.curTreeNode = {};
      this.isAddOrg = false;
    },
    //编辑组织
    nodeEdit(data) {
      this.orgTitle = "组织编辑";
      this.isAddOrg = true;
      this.isEdit = true;
      this.curTreeNode = { ...data };
      this.orgname = data.label;
    },
    //删除组织
    nodeDel(node, data) {
      this.$confirm("删除组织, 是否继续?", "提示", {
        closeOnClickModal: false,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          orgAPI
            .orgDel(data.id)
            .then((res) => {
              let pid = data.pid != 0 ? data.pid : 0;
              this.refreshNodeBy(pid);
            })
            .catch((err) => {
              this.$message.error(err.message);
            });
        })
        .catch(() => {});
    },
    //新增节点保存
    saveOrg() {
      this.saveLoading = true;
      //请求成功后跳转回列表页面
      if (!this.isEdit) {
        orgAPI
          .orgAdd({ pid: this.curTreeNode.id, orgname: this.orgname })
          .then((res) => {
            this.refreshNodeBy(this.curTreeNode.id);
            this.isAddOrg = false;
            this.saveLoading = false;
          })
          .catch((err) => {
            this.saveLoading = false;
            this.$message.error(err.message);
          });
      } else {
        orgAPI
          .orgEdit({
            id: this.curTreeNode.id,
            pid: this.curTreeNode.pid,
            orgname: this.orgname,
          })
          .then((res) => {
            this.refreshNodeBy(this.curTreeNode.pid);
            this.isAddOrg = false;
            this.saveLoading = false;
          })
          .catch((err) => {
            this.saveLoading = false;
            this.$message.error(err.message);
          });
      }
    },
    //组织人员列表
    getPeopleList(val) {
      let parmars = {
        orgid: val,
        pageNo: 1,
        pageSize: 1000,
      };
      orgAPI
        .getOrgPeopleList(parmars)
        .then((res) => {
          this.tableData = [...res.data];
          this.peoloading = false;
        })
        .catch((err) => {
          this.peoloading = false;
          this.tableData = [];
          this.$message.error(err.message);
        });
    },
    //新增人员
    addUser(isMore) {
      if (this.addPeople.orgid) {
        this.isAddUser = true;
        this.isMore = isMore;
        this.formTitle = isMore ? "批量添加人员" : "添加人员";
        this.editRow = {
          orgname: this.addPeople.orgname,
          orgid: this.addPeople.orgid,
          is_outer: 0,
          is_reiviewed: 1,
        };
        this.visible = true;
      } else {
        this.$message.warning("请先点击左侧行高亮选中");
      }
    },
    editPeople(data) {
      this.isAddUser = false;
      this.isMore = false;
      this.formTitle = "编辑人员";
      this.editRow = {
        id: data.id,
        uid: data.uid,
        orgid: this.addPeople.orgid,
        orgname: data.orgname,
        name: data.name,
        kp: data.kp,
        is_outer: data.is_outer,
        is_reiviewed: data.is_reiviewed,
      };
      this.visible = true;
    },
    delPeople(data) {
      this.$confirm("删除人员, 是否继续?", "提示", {
        closeOnClickModal: false,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.peoloading = true;
          orgAPI
            .orgPeopleDel(data.id)
            .then((res) => {
              this.getPeopleList(this.addPeople.orgid);
            })
            .catch((err) => {
              this.$message.error(err.message);
            });
        })
        .catch(() => {});
    },
    submitForm(val) {
      // console.log(val, "val");
      let parmars = {
        uid: val.uid,
        orgid: val.orgid,
        name: val.name,
        kp: val.kp,
        is_outer: val.is_outer,
        is_reiviewed: val.is_reiviewed,
      };
      if (this.isAddUser) {
        orgAPI
          .orgPeopleAdd({
            ...parmars,
          })
          .then((res) => {
            this.$refs.form.cancel();
            this.peoloading = true;
            this.getPeopleList(this.addPeople.orgid);
          })
          .catch((err) => this.$message.error(err.message));
      } else {
        orgAPI
          .orgPeopleEdit({
            id: val.id,
            ...parmars,
          })
          .then((res) => {
            this.$refs.form.cancel();
            this.peoloading = true;
            this.getPeopleList(this.addPeople.orgid);
          })
          .catch((err) => this.$message.error(err.message));
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.box-title-position {
  position: relative;
  .add-btn {
    position: absolute;
    right: 0;
    top: -3px;
    &:nth-child(1) {
      right: 110px;
    }
  }
}
.custom-tree-node {
  font-size: 14px;
  display: flex;
  align-items: center;
  width: 100%;
  & > span:nth-child(1) {
    flex: 2;
  }
}
.org-content {
  margin-top: 30px;
  display: flex;
  align-items: center;
}
.org-label {
  font-size: 14px;
  width: 85px;
  display: inline-block;
}
.btn-box {
  text-align: right;
  padding-top: 30px;
}
</style>